package com.topvision.camerasdk.album.test;

import android.annotation.SuppressLint;
import android.app.Instrumentation;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.PixelFormat;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.topvision.camerasdk.R;
import com.topvision.commomsdk.view.CircleProgressView;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

//xunbeibei

//xunbeibei

/**
 * 头部控制核心Service
 *
 * @author Administrator
 */
public class TopWindowServiceEpson extends Service {

    // 移动阀值
    public int MOVE_THORESHOLD = 1;

    // ACTION
    public static String ACTION_CLICK = "click";
    public static String ACTION_BACK = "back";
    public static String ACTION_PREVIOUS = "previos";
    public static String ACTION_NEXT = "next";
    public static String ACTION_TAKE_PHOTO = "take_photo";
    public static String ACTION_BACK_HOME = "back_home";
    public static String ACTION_SHOW_SETTING = "show_setting";
    public static String OPERATION = "operation";

    // 一些常量
    public static String BASE_PACKAGE = "com.topvision.gsj.launcher";
    public static String LAUNCHER_PACKAGE = BASE_PACKAGE + ".LauncherActivity";
    public static final String SETTING_ACTIVITY_PACKAGE = "com.topvision.gsj.headtrack.HeadActivity";
    public final String PHOME_CAMERA_PACKAGE = "com.topvision.gsj.phonecamera";

    // Hanlder事件
    public final int HANDLE_FLOAT_VIEW_MOVE = 1;
    public final int HANDLE_FLOAT_VIEW_HIDDEN = 2;
    public final int HANDLE_FLOAT_VIEW_SHOW = 3;
    public final int HANDLE_FLOAT_VIEW_DRAG = 4;
    public final int HANDLE_FLOAT_VIEW_START_PROGRESS = 5;

    // 模拟事件类
    Instrumentation instrumentation;
    // 传感器
    private SensorManager manager;
    private MySensorListener listener;

    private LayoutParams params;
    private WindowManager wm;

    // 悬浮按钮视图
    View view;
    // xunbeibei
    private LayoutParams dataParams;
    View dataView;
    // xunbeibei
    CircleProgressView circleProgressView;

    private int screenWidth, midWidth, screenHeight, midHeight;
    // 悬浮按钮是否添加
    boolean isAdded = false;
    // 悬浮按钮是否初始化
    boolean isInit = false;
    // 悬浮按钮是否处于激活状态,只有当处于激活状态时才能触发点击操作
    public boolean isActive = false;
    private int reinit = 0;
    // 判断是否处于行动状态
    boolean actionFlag = false;
    // 记录当前位置和上次的移動位置
    private float origin_width, last_origin_width, origin_height,
            last_origin_height;
    // 记录一些时间
    private long current_click_date, topLastStayTime, leftLastStayTime,
            rightLastStayTime;
    // 最大停留時間,以下是在最左側和最右側停留的時間
    private long MaxLeftStayTime = 1000, MaxRightStayTime = 1000;
    // 顶部
    private long MaxTopStayTime = 2000;
    // 当前Activity的className名称
    private String currentClassName = "";

    private long reinitTime = 0;
    MyReceiver myReceiver;
    Context context;
    float x_value = 0;
    float y_value = 0;
    float[] values;

    // xunbeibei
    private static final String TOPVISION_SENSOR_RANGE = "topvision_sensor_range";
    private static final int DEFAULT_SENSOR_RANGE_VALUE = 45;
    float x_offset = 0;
    float y_offset = 0;
    float z_offset = 0;
    boolean calibrateStatus = false;
    TextView orien_X;
    TextView orien_Y;
    TextView orien_Z;
    DecimalFormat angel = new DecimalFormat("0.000000");

    // xunbeibei

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        printAllSensor();
        initObject();
        initScreenParams();
        createFloatView();
        // xunbeibei
        createDataView();
        initSensorOffset();
        // xunbeibei
        showPoint();
        setParas();
        registerBroadCast();
        currentClassName = HeadTrackUtil
                .getCurrentActivityName(getApplicationContext());
    }

    private void printAllSensor() {
        SensorManager sm = (SensorManager) getSystemService(SENSOR_SERVICE); // 获取系统的传感器服务并创建实例

        List<Sensor> list = sm.getSensorList(Sensor.TYPE_ALL); // 获取传感器的集合
        for (Sensor sensor : list) {
            Log.e("sensor", sensor.getName());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return 0;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    boolean destroyFlag = false;

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (isAdded) {
            hidePoint();
        }
        destroyFlag = true;
        unRegisterSensor();
        unRegisterBroadCast();
    }

    /**
     * 初始化一些需要用到的对象
     */
    private void initObject() {
        instrumentation = new Instrumentation();
        wm = (WindowManager) getApplicationContext().getSystemService(
                Context.WINDOW_SERVICE);
        registerSensor();
    }

    /**
     * 注册一些sensor传感器
     */
    private void registerSensor() {
        manager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        listener = new MySensorListener();

        manager.registerListener(listener,
                manager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
                SensorManager.SENSOR_DELAY_NORMAL);

        manager.registerListener(listener,
                manager.getDefaultSensor(Sensor.TYPE_GYROSCOPE),
                SensorManager.SENSOR_DELAY_NORMAL);

        // orientation
        manager.registerListener(listener,
                manager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_FASTEST);
        // orientation

    }

    /**
     * 取消传感器注册
     */
    private void unRegisterSensor() {
        if (manager != null) {
            manager.unregisterListener(listener);
        }
    }

    /**
     * 创建悬浮按钮
     */
    private void createFloatView() {

        view = LayoutInflater.from(getApplicationContext()).inflate(
                R.layout.circle_progress_view, null);
        circleProgressView = (CircleProgressView) view
                .findViewById(R.id.circleProgressbar);
        circleProgressView.setProgress(0);

        params = new LayoutParams();
        params.type = LayoutParams.TYPE_SYSTEM_ALERT;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = screenWidth / 2;
        params.y = screenHeight / 2;
        params.format = PixelFormat.RGBA_8888;
        params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
                | LayoutParams.FLAG_NOT_FOCUSABLE
                | LayoutParams.FLAG_NOT_TOUCHABLE;

        params.width = 35;
        params.height = 35;

    }

    // xunbeibei
    private void createDataView() {

        dataView = LayoutInflater.from(getApplicationContext()).inflate(
                R.layout.data, null);

        orien_X = (TextView) dataView.findViewById(R.id.orien_x);
        orien_Y = (TextView) dataView.findViewById(R.id.orien_y);
        orien_Z = (TextView) dataView.findViewById(R.id.orien_z);

        dataParams = new LayoutParams();
        dataParams.type = LayoutParams.TYPE_SYSTEM_ALERT;
        dataParams.x = 0;
        dataParams.y = 0;
        dataParams.format = PixelFormat.RGBA_8888;
        dataParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
                | LayoutParams.FLAG_NOT_FOCUSABLE
                | LayoutParams.FLAG_NOT_TOUCHABLE;

        dataParams.width = LayoutParams.WRAP_CONTENT;
        dataParams.height = LayoutParams.WRAP_CONTENT;

    }

    // xunbeibei

    /**
     * 显示悬浮按钮
     */
    private void showPoint() {
        wm.addView(view, params);
        // xunbeibei
        //  wm.addView(dataView, dataParams);
        // xunbeibei
        isAdded = true;
    }

    /**
     * 隐藏悬浮按钮
     */
    private void hidePoint() {
        wm.removeView(view);
        // xunbeibei
        wm.removeView(dataView);
        // xunbeibei
        isAdded = false;
    }

    class MySensorListener implements SensorEventListener {
        // 用來记录上一次加速度x,y,z的值
        BigDecimal previosACCEX = new BigDecimal(100);
        BigDecimal previosACCEY = new BigDecimal(100);
        BigDecimal previosACCEZ = new BigDecimal(100);
        // 是否移动
        boolean isMove = false;
        // 阀值
        private float number = 0.1f;
        private float state_x = 0.1f;
        private float state_y = 0.1f;
        // 比例值
        private final static int DEGREE_THRESHOLD_TOBORDER = 40;
        private final static int DEGREE_THRESHOLD_TOBORDER_y = 40;

        // xunbeibei
        private final static int MAX_ORIENTATION_ANGEL = 45;

        // xunbeibei

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }

        @Override
        public void onSensorChanged(SensorEvent event) {
            // 线性加速度,去除了重力因素
            if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {
                // if (isAdded) {
                float x = event.values[0];
                float y = event.values[1];
                float z = event.values[2];
                BigDecimal ACCEX = new BigDecimal(x);
                ACCEX = ACCEX.setScale(2, BigDecimal.ROUND_HALF_UP);

                BigDecimal ACCEY = new BigDecimal(y);
                ACCEY = ACCEY.setScale(2, BigDecimal.ROUND_HALF_UP);

                BigDecimal ACCEZ = new BigDecimal(z);
                ACCEZ = ACCEZ.setScale(2, BigDecimal.ROUND_HALF_UP);

                if (previosACCEX.toString().equals("100")
                        || previosACCEY.equals("100")
                        || previosACCEZ.toString().equals("100")) {
                    previosACCEX = ACCEX;
                    previosACCEY = ACCEY;
                    previosACCEZ = ACCEZ;
                    return;
                }
                float betweenACCEX = Math.abs(ACCEX.subtract(previosACCEX)
                        .floatValue());
                float betweenACCEY = Math.abs(ACCEY.subtract(previosACCEY)
                        .floatValue());
                float betweenACCEZ = Math.abs(ACCEZ.subtract(previosACCEZ)
                        .floatValue());
                if (betweenACCEX > number || betweenACCEY > number
                        || betweenACCEZ > number) {
                    isMove = true;
                    // System.out.println("betweenACCEX="
                    // + betweenACCEX
                    // + ",betweenACCEY="
                    // + betweenACCEY
                    // + ",betweenACCEZ="
                    // + betweenACCEZ);
                } else {
                    isMove = false;
                }

                previosACCEX = ACCEX;
                previosACCEY = ACCEY;
                previosACCEZ = ACCEZ;
                // }

            }
            // 陀螺仪
            else if (event.sensor.getType() == Sensor.TYPE_ORIENTATION) {
                boolean heightFlag = false, widthFlag = false;
                // 重新绘制悬浮点,並做了一個动画效果
                if (reinit != 0) {
                    if (reinit == 1) {
                        reinit = 2;
                        simulateDrag((int) origin_width, (int) origin_height,
                                midWidth, midHeight, 3000);
                    } else if (reinit == 3) {
                        if ((reinitTime + 2000) < System.currentTimeMillis()) {
                            reinit = 0;
                        }
                    }
                    return;
                }

                // currentClassName = HeadTrackUtil
                // .getCurrentActivityName(getApplicationContext());
                // 在某些页面中悬浮点必须需要显示
                if (TopWindowServiceEpson.LAUNCHER_PACKAGE
                        .equals(currentClassName)
                        || TopWindowServiceEpson.SETTING_ACTIVITY_PACKAGE
                        .equals(currentClassName)) {
                    if (!isAdded) {
                        params.x = screenWidth / 2;
                        params.y = screenHeight / 2;
                        showPoint();
                    }

                }

                if (!isInit) {
                    // 初始化起始位置
                    origin_width = midWidth;
                    origin_height = midHeight;
                    if (current_click_date == 0) {
                        current_click_date = System.currentTimeMillis();
                    }
                } else {
                    values = event.values;
                    x_value = Math.abs(values[0]);
                    y_value = Math.abs(values[1]);
                    // 用來標示是否移动

                    if (!isMove) {
                        return;
                    }

                    // if (isMove) {

                    // xunbeibei
                    orien_X.setText("X Data: " + angel.format(event.values[0]));
                    orien_Y.setText("Y Data: " + angel.format(event.values[1]));
                    orien_Z.setText("Z Data: " + angel.format(event.values[2]));
                    if (getCalibrateStatus()) {
                        calibrateHeadControl(values);
                        setCalibrateStatus(false);
                    }

                    origin_width = midWidth
                            + (int) ((values[0] - x_offset) * midWidth / getMaxRangeValue());
                    origin_height = midHeight
                            + (int) ((values[1] - y_offset) * midHeight / getMaxRangeValue());
                    widthFlag = true;
                    heightFlag = true;
                    // xunbeibei
                    /*
                     * if (values[0] > 0 && values[0] >= state_x) {
					 * origin_height = origin_height - Math.abs((x_value *
					 * midHeight) / DEGREE_THRESHOLD_TOBORDER_y); heightFlag =
					 * true; } else if (values[0] < 0 && values[0] <= -state_x)
					 * { origin_height = origin_height + Math.abs((x_value *
					 * midHeight) / DEGREE_THRESHOLD_TOBORDER_y); heightFlag =
					 * true; }
					 * 
					 * if (values[1] > 0 && values[1] >= state_y) { origin_width
					 * = origin_width - Math.abs((y_value * midWidth) /
					 * DEGREE_THRESHOLD_TOBORDER); widthFlag = true; } else if
					 * (values[1] < 0 && values[1] <= -state_y) { origin_width =
					 * origin_width + Math.abs((y_value * midWidth) /
					 * DEGREE_THRESHOLD_TOBORDER); widthFlag = true; }
					 */
                    // }

                }

                isActive = heightFlag || widthFlag;
                if (origin_height <= 0) {
                    origin_height = 0;
                    isActive = false;
                    doTopEvent();
                } else {
                    topLastStayTime = 0;
                }
                if (origin_height >= screenHeight) {
                    origin_height = screenHeight;
                }
                if (origin_width <= 0) {
                    origin_width = 0;
                    isActive = false;
                    if (isAdded) {
                        doLeftEvent();
                    }
                } else if (origin_width > 0 && origin_width < midWidth) {
                    leftLastStayTime = 0;
                }
                if (origin_width >= screenWidth) {
                    origin_width = screenWidth;
                    isActive = false;
                    if (isAdded) {
                        doRightEvent();
                    }

                }
                // 在LauncherActivity中靠左側兩秒執行翻頁
                else if (origin_width > midWidth && origin_width < screenWidth) {
                    rightLastStayTime = 0;
                }
                isInit = true;
                if (!isAdded) {
                    return;
                }

                if (isActive) {
                    // 算出上一次和這一次差值
                    float betweenWidth = Math.abs(last_origin_width
                            - origin_width);
                    float betweenHeight = Math.abs(last_origin_height
                            - origin_height);

                    if (betweenWidth < MOVE_THORESHOLD
                            && betweenHeight < MOVE_THORESHOLD) {
                        // 停留1.5秒就行点击事件
                        if ((current_click_date + 1500) < System
                                .currentTimeMillis()) {
                            handler.sendEmptyMessage(2000);
                            current_click_date = System.currentTimeMillis();
                            // 避免重复转圈
                            // if (!actionFlag) {
                            // // processSimulateAction(origin_width,
                            // origin_height,
                            // // params.width, params.height, ACTION_CLICK,
                            // // currentClassName);
                            // // startProgress(origin_width, origin_height);
                            // current_click_date = System.currentTimeMillis();
                            // actionFlag = true;
                            // }

                        }
                    } else {
                        // 关闭转圈线程
                        // stoptimertask();
                        // 发送消息变化UI
                        Message msg = Message.obtain();
                        msg.arg1 = (int) origin_width;
                        msg.arg2 = (int) origin_height;
                        msg.what = HANDLE_FLOAT_VIEW_MOVE;
                        handler.sendMessage(msg);
                        current_click_date = System.currentTimeMillis();
                        actionFlag = false;
                        // 重新賦值
                        last_origin_width = origin_width;
                        last_origin_height = origin_height;

                    }
                } else {
                    current_click_date = System.currentTimeMillis();
                }

            }
        }
    }

    /**
     * 处理一些Action事件
     *
     * @param x
     * @param y
     * @param width
     * @param height
     * @param action
     * @param currentClassName
     * @return
     */
    private boolean processSimulateAction(final float x, final float y,
                                          int width, int height, String action, String currentClassName) {
        if (ACTION_CLICK.equals(action)) {
            // 妯℃嫙鐐瑰嚮浜嬩欢璇ユ柟娉曞繀椤诲湪瀛愮嚎绋嬩腑鍘绘搷浣�
            simulateClick(view, x, y);

        }
        return true;
    }

    /**
     * 停留頂部兩秒事件处理
     */
    public void doTopEvent() {
//        if (topLastStayTime == 0) {
//            topLastStayTime = System.currentTimeMillis();
//        }
//        // 對不同Activity中相同事件做不同处理
//        if (LAUNCHER_PACKAGE.equals(currentClassName)
//                || currentClassName.equals(SETTING_ACTIVITY_PACKAGE)) {
//            // 超过MaxTopStayTime时间
//            if ((topLastStayTime + MaxTopStayTime) < System.currentTimeMillis()) {
//                HeadActivity.isAdd = !HeadActivity.isAdd;
//                if (HeadActivity.isAdd) {
//                    Intent intent = new Intent(getApplication(),
//                            HeadActivity.class);
//                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    startActivity(intent);
//                } else {
//                    if (HeadActivity.instance != null) {
//                        HeadActivity.instance.finish();
//                    }
//
//                }
//
//                topLastStayTime = 0;
//            }
//
//            return;
//        }
//        // 在其他頁面中做悬浮点隐藏或者显示操作
//        else {
//            if ((topLastStayTime + MaxTopStayTime) < System.currentTimeMillis()) {
//                isAdded = !isAdded;
//                if (isAdded) {
//                    // 显示
//                    handler.sendEmptyMessage(HANDLE_FLOAT_VIEW_SHOW);
//                } else {
//                    // 隐藏
//                    handler.sendEmptyMessage(HANDLE_FLOAT_VIEW_HIDDEN);
//                }
//
//                isActive = false;
//                isInit = false;
//                current_click_date = System.currentTimeMillis();
//                topLastStayTime = 0;
//                if (isAdded) {
//                    reinitTime = System.currentTimeMillis();
//                    reinit = 1;
//                    return;
//                }
//
//            }
//        }
    }

    /**
     * 左側停留事件
     */
    public void doLeftEvent() {
        // LauncherActivity
        if (!TextUtils.isEmpty(currentClassName)
                && currentClassName.equals(LAUNCHER_PACKAGE)) {
            if (leftLastStayTime == 0) {
                leftLastStayTime = System.currentTimeMillis();
            }
            if ((leftLastStayTime + MaxLeftStayTime) < System
                    .currentTimeMillis()) {
                Intent intent = new Intent(ACTION_PREVIOUS);
                sendBroadcast(intent);
                leftLastStayTime = 0;
            }

        }
        return;
    }

    /**
     * 右侧事件
     */
    public void doRightEvent() {
        if (!TextUtils.isEmpty(currentClassName)
                && currentClassName.equals(LAUNCHER_PACKAGE)) {
            if (rightLastStayTime == 0) {
                rightLastStayTime = System.currentTimeMillis();
            }
            if ((rightLastStayTime + MaxRightStayTime) < System
                    .currentTimeMillis()) {
                Intent intent = new Intent(ACTION_NEXT);
                sendBroadcast(intent);
                rightLastStayTime = 0;
            }

        }
        return;
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 移動悬浮点
                case HANDLE_FLOAT_VIEW_MOVE:
                    params.x = msg.arg1;
                    params.y = msg.arg2;
                    if (!destroyFlag) {
                        wm.updateViewLayout(view, params);
                    }

                    break;
                // 绘制悬浮点
                case HANDLE_FLOAT_VIEW_DRAG:
                    if (isAdded) {
                        params.x = msg.arg1;
                        params.y = msg.arg2;
                        wm.updateViewLayout(view, params);
                        origin_width = screenWidth / 2;
                        origin_height = screenHeight / 2;
                        reinit = 3;
                    }
                    break;
                case HANDLE_FLOAT_VIEW_START_PROGRESS:
                    int progress = (Integer) msg.obj;
                    circleProgressView.setProgressNotInUiThread(progress);
                    break;
                // 显示悬浮点
                case HANDLE_FLOAT_VIEW_SHOW:
                    showPoint();
                    break;
                // 隐藏
                case HANDLE_FLOAT_VIEW_HIDDEN:
                    hidePoint();
                    break;
                case 2000:
                    Toast.makeText(context, "click...", Toast.LENGTH_SHORT).show();
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 模拟点击事件
     *
     * @param view
     * @param x
     * @param y
     */
    private void simulateClick(View view, final float x, final float y) {
        new Thread(new Runnable() {
            public void run() {
                final float correctX = x + params.width / 2;
                final float correctY = y + params.height / 2;
                long downTime = SystemClock.uptimeMillis();
                final MotionEvent downEvent = MotionEvent.obtain(downTime,
                        downTime, MotionEvent.ACTION_DOWN, correctX, correctY,
                        0);
                downTime += 1000;
                final MotionEvent upEvent = MotionEvent.obtain(downTime,
                        downTime, MotionEvent.ACTION_UP, correctX, correctY, 0);
                instrumentation.sendPointerSync(downEvent);
                instrumentation.sendPointerSync(upEvent);
                downEvent.recycle();
                upEvent.recycle();
            }
        }).start();

    }

    /**
     * 開始转圈
     *
     * @param x
     * @param y
     */
    protected void startProgress(float x, float y) {
        handler.removeMessages(1001);
        if (timer == null) {
            timer = new Timer();
        }
        if (timerTask == null) {
            timerTask = new progressTimerTask(0, x, y);
        } else {
            timerTask.cancel();
            timerTask = new progressTimerTask(0, x, y);
        }

        timer.schedule(timerTask, 100, 100);
    }

    /**
     * 鍏抽棴杞湀
     */
    private void stopTimerTask() {
        handler.removeMessages(1001);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }

        circleProgressView.setProgressNotInUiThread(0);
    }

    Timer timer = null;
    TimerTask timerTask = null;

    class progressTimerTask extends TimerTask {
        int progress = 0;
        float x;
        float y;

        public progressTimerTask(int progress, float x, float y) {
            this.progress = progress;
            this.x = x;
            this.y = y;
        }

        @Override
        public void run() {
            if (progress <= 100) {
                progress = progress + 5;
                Message message = handler
                        .obtainMessage(HANDLE_FLOAT_VIEW_START_PROGRESS);
                message.obj = progress;
                message.sendToTarget();
            } else {
                stopTimerTask();
                processSimulateAction(origin_width, origin_height,
                        params.width, params.height, ACTION_CLICK,
                        currentClassName);
                isActive = false;
                current_click_date = System.currentTimeMillis();
            }

        }

    }

    /**
     * 初始化一些參數值
     */
    private void initScreenParams() {
        this.screenWidth = this.getResources().getDisplayMetrics().widthPixels;
        this.screenHeight = this.getResources().getDisplayMetrics().heightPixels;
        midWidth = screenWidth / 2;
        midHeight = screenHeight / 2;

    }

    /**
     * 对不同设备设置一些不同的阀值
     */
    private void setParas() {
        MOVE_THORESHOLD = 1;
    }

    /**
     * 绘画悬浮点,主要做个从某处移动到某处的一个动画效果
     *
     * @param startWidth
     * @param startHeight
     * @param toWidth
     * @param toHeight
     * @param timePeroid
     */
    private void simulateDrag(int startWidth, int startHeight, int toWidth,
                              int toHeight, int timePeroid) {

        int widthGap = toWidth - startWidth;
        int heightGap = toHeight - startHeight;
        int times = timePeroid / 60 + (timePeroid % 60 == 0 ? 0 : 1);
        int widthPer = widthGap / times;
        int lastWidhtPer = widthGap % times;
        if (lastWidhtPer == 0) {
            lastWidhtPer = widthPer;
        }
        int heightPer = heightGap / times;
        int lastHeightPer = heightGap % times;
        if (lastHeightPer == 0) {
            lastHeightPer = heightPer;
        }
        for (int i = 0; i < (times - 1); i++) {
            startWidth += widthPer;
            startHeight += heightPer;
            Message msg = Message.obtain();
            msg.arg1 = startWidth;
            msg.arg2 = startHeight;
            msg.what = HANDLE_FLOAT_VIEW_MOVE;
            handler.sendMessageDelayed(msg, 100);
        }
        startWidth += lastWidhtPer;
        startHeight += lastHeightPer;
        Message msg = Message.obtain();
        msg.arg1 = startWidth;
        msg.arg2 = startHeight;
        msg.what = HANDLE_FLOAT_VIEW_DRAG;
        handler.sendMessageDelayed(msg, 100);
    }

    /**
     * 頭部矫正
     */
    private void checkHead() {
        Message message = handler.obtainMessage(HANDLE_FLOAT_VIEW_MOVE);
        message.arg1 = midWidth;
        message.arg2 = midHeight;
        origin_width = midWidth;
        origin_height = midHeight;
        message.sendToTarget();
    }

    private void registerBroadCast() {
        if (myReceiver == null) {
            myReceiver = new MyReceiver();
        }
        //Intent.ACTION_CAMERA_BUTTON
        IntentFilter intentFilter = new IntentFilter();
        // 鐩戝惉灞忓箷寮�叧
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        // xunbeibei
        intentFilter.addAction(TopIntent.SENSOR_CALIBRATE);
        // xunbeibei
        registerReceiver(myReceiver, intentFilter);

    }

    /**
     * 取消廣播註冊
     */
    private void unRegisterBroadCast() {
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }

    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 头部矫正
//            if (Intent.ACTION_CAMERA_BUTTON.equals(action)) {
//                if (!PHOME_CAMERA_PACKAGE.equals(currentClassName) && isAdded) {
//                    checkHead();
//                }
//            }
//            else
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                current_click_date = System.currentTimeMillis();
                registerSensor();

            }
            // 屏幕变暗,取消传感器监听,减少cpu
            else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                unRegisterSensor();
                stopTimerTask();
                isActive = false;
            }
            // xunbeibei
            else if (action.equals(TopIntent.SENSOR_CALIBRATE)) {
                Log.d("HeadControl", "HeadControl Calibrate");
                setCalibrateStatus(true);
            }
            // xunbeibei
        }

    }

    // xunbeibei
    private void initSensorOffset() {
        int rotation = getDisplayRotation();
        Log.d("HeadControl", "initSensorOffset rotation = " + rotation);
        x_offset = 270 - rotation;
        y_offset = -90;
        z_offset = 0;
    }

    private int getDisplayRotation() {
        int displayRotation = wm.getDefaultDisplay().getRotation();
        switch (displayRotation) {
            case Surface.ROTATION_0:
                return 0;
            case Surface.ROTATION_90:
                return 90;
            case Surface.ROTATION_180:
                return 180;
            case Surface.ROTATION_270:
                return 270;
        }
        return 0;
    }

    private void setCalibrateStatus(boolean status) {
        calibrateStatus = status;
    }

    private boolean getCalibrateStatus() {
        return calibrateStatus;
    }

    private void calibrateHeadControl(float[] values) {
        Log.d("HeadControl", "calibrateHeadControl values[0] = " + values[0]
                + " values[1] = " + values[1]);
        x_offset = values[0];
        y_offset = values[1];
        z_offset = values[2];
    }

    private int getMaxRangeValue() {
        ContentResolver resolver = context.getContentResolver();
        int maxSensorRange = Settings.System.getInt(resolver,
                TOPVISION_SENSOR_RANGE, DEFAULT_SENSOR_RANGE_VALUE);
        return maxSensorRange;
    }
    // xunbeibei

}
